package com.example.rabbitmq.producer.delay.service;/**
 * ClassName: CustomSender <br/> Description: 延时消息发送<br/> date: 2022/1/24 15:02<br/>
 *
 * @author chenzhian<br />
 * @version
 */

import com.example.common.config.RabbitMQConfig;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: chenzhian
 * @Date: 2022/1/24 15:02
 * @Description:
 */
@Service
public class CustomSender {

  //日期格式化
  private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  @Resource
  private RabbitTemplate rabbitTemplate;

  public void sendMsg(String queueName, String msg) throws Exception {
    System.out.println("消息发送时间：" + sdf.format(new Date()));

    rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DELAYED_EXCHANGE, queueName, msg,
        //消息发送前的处理器
        new MessagePostProcessor() {
          //消息延迟5秒
          @Override
          public Message postProcessMessage(Message message) throws AmqpException {
            message.getMessageProperties().setHeader("x-delay", 5000);
            return message;
          }
        });
  }
}